package com.share.demo.thread;

/**
 * created by caifan 2017/11/30
 */
public class VolatileDemo {
    int x = 0;
    volatile  boolean v = false;
    public void writer() {
        x = 42;
        v = true;
    }

    public void reader() {
        while (!v) {
            System.out.println(x);
            //uses x - guaranteed to see 42.
        }
        System.out.println("悟空是个猴子");

    }

    public static void main(String[] args) throws InterruptedException {
        final VolatileDemo volatileExample=new VolatileDemo();
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                volatileExample.reader();
            }
        });
        thread.start();
        Thread.sleep(1000);
        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                volatileExample.writer();
            }
        });
        thread2.start();

    }
}
